package com.efounder.zone.widget;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.AsyncTask;
import androidx.annotation.Nullable;
import android.util.AttributeSet;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.request.RequestOptions;
import com.efounder.chat.activity.ChatWebViewActivity;
import com.efounder.chat.activity.PlayerActivity;
import com.efounder.chat.db.WeChatDBManager;
import com.efounder.chat.utils.ImageUtil;
import com.efounder.chat.utils.PansoftCloudUtil;
import com.efounder.chat.widget.ChatTextView;
import com.efounder.constant.EnvironmentVariable;
import com.efounder.mobilecomps.contacts.User;
import com.efounder.pansoft.chat.record.voice.DensityUtil;
import com.efounder.view.RoundFrameLayout;
import com.efounder.zone.R;
import com.efounder.zone.bean.TalksBean;
import com.utilcode.util.ScreenUtils;

import org.json.JSONArray;
import org.json.JSONObject;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;

import cn.bingoogolapple.photopicker.widget.BGANinePhotoLayout;

/**
 * Created by Richard on 2018/5/9.
 * <p>
 * 空间的文字，图片 视频 和网页View
 */

public class MutiContentDisplayView520 extends LinearLayout {

    private ChatTextView tvContentDescribe;
    private BGANinePhotoLayout mNinePhotoLayout;
    private ZoneNinePhotoLayout zoneNinePhotoLayout;
    // private RelativeLayout videoContainer;
    private RoundFrameLayout videoContainer;
    private ImageView mVideoCover;
    //    private LinearLayout imgStartBgLl;
    private ThumbDisplayListener listener;
    private LinearLayout mPhotoContainer;
    private TextView mTransmitSourceUserName;
    private ChatTextView tvTransmitContentDescirbe;
    private MobileZoneWebView mWebView;
    private int type;
    private Context mContext;


    public MutiContentDisplayView520(Context context) {
        super(context, null);
    }

    public MutiContentDisplayView520(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs, -1);
        initView();
        mContext = context;
    }

    public MutiContentDisplayView520(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    private void initView() {

        View.inflate(getContext(), R.layout.mobile_zone_item_text_video_image, this);
        tvContentDescribe = (ChatTextView) findViewById(R.id.mobile_zone_content_describe);
        mNinePhotoLayout = findViewById(R.id.mobile_zone_content_photo);
        zoneNinePhotoLayout = findViewById(R.id.mobile_zone_content_photo1);
        //videoContainer = (RelativeLayout) findViewById(R.id.mobile_zone_content_video_container);
        videoContainer = (RoundFrameLayout) findViewById(R.id.mobile_zone_content_video_container);

//        imgStartBgLl = (LinearLayout) findViewById(R.id.video_cover_start);//播放图标
        mVideoCover = (ImageView) findViewById(R.id.video_cover_1);//显示预览图
        mPhotoContainer = (LinearLayout) findViewById(R.id.mobile_zone_photo_container);
        mTransmitSourceUserName = (TextView) findViewById(R.id.mobile_zone_transmit_source_username);
        tvTransmitContentDescirbe = (ChatTextView) findViewById(R.id.mobile_zone_transmit_content_describe);
        mWebView = findViewById(R.id.mobile_zone_webview);
//        progressView = (SendImgProgressView) findViewById(com.efounder.chat.R.id.progressView);//上传进度
        int videoWidth = ScreenUtils.getScreenWidth() - DensityUtil.dp2px(20);
        int videoHeight = videoWidth * 2 / 3;
        ViewGroup.LayoutParams layoutParams = videoContainer.getLayoutParams();
        layoutParams.height = videoHeight;
        layoutParams.width = videoWidth;
        videoContainer.setLayoutParams(layoutParams);
        ViewGroup.LayoutParams layoutParams1 = mVideoCover.getLayoutParams();
        layoutParams1.height = videoHeight;
        layoutParams1.width = videoWidth;
        mVideoCover.setLayoutParams(layoutParams1);
        // mVideoCover.setBackgroundDrawable(null);

//        int width = ScreenUtils.widthPixels(getContext()) - DensityUtil.dp2px(20);
//        tvContentDescribe.initWidth(width);
//        //最多显示8行
//        tvContentDescribe.setMaxLines(3);
    }

    /**
     * 调用此方法显示内容
     *
     * @param objBean
     */
    public void display(TalksBean.ObjBean objBean) {
        try {
            Object transmitContent = objBean.getTransmitContent();
            Object transmitSourceUserid = objBean.getTransmitSourceUserid();

            JSONObject postContent = new JSONObject(objBean.getPostContent());
            String text = postContent.optString("text");
            if (null == text || "".equals(text)) {
                tvContentDescribe.setVisibility(GONE);
            } else {
                tvContentDescribe.setVisibility(VISIBLE);
            }
            tvContentDescribe.setText(text);
            //查询取出用户名
            String userName = "";
            if (null != transmitSourceUserid) {
                User user = WeChatDBManager.getInstance().getOneUserById(Integer.parseInt(transmitSourceUserid.toString()));
                userName = user.getNickName();
            }

            int type = postContent.optInt("type");

            if (null != transmitContent && null != transmitSourceUserid) {
                //是转发的
                transmitStyle(transmitContent, text, userName);
            } else {
                //是原创的
                ownStyle(userName, type);
            }


            //1：纯文本 2：文本+图片 3：文本+视频 4:文字+网页
            mWebView.setVisibility(GONE);

            if (type == 2) {
                JSONArray imgArray = postContent.optJSONArray("images");
                ArrayList<String> imgs = new ArrayList<>();
                for (int i = 0; i < imgArray.length(); i++) {
                    imgs.add((String) imgArray.opt(i));
                }
                if (imgs.size() > 0)

                    mNinePhotoLayout.setVisibility(View.GONE);
                zoneNinePhotoLayout.setVisibility(View.VISIBLE);
//                  mNinePhotoLayout.setData(imgs);
                zoneNinePhotoLayout.setData(imgs);
                videoContainer.setVisibility(GONE);
            } else if (type == 3) {
                mNinePhotoLayout.setVisibility(View.GONE);
                zoneNinePhotoLayout.setVisibility(View.GONE);
                videoContainer.setVisibility(VISIBLE);
                final String videoUrl = postContent.optString("video");
                //从url 获取文件名（文件ID）
                final String videoName = PansoftCloudUtil.getPansoftCloudFileId(videoUrl);
                //bitmapPool获取bitmap
                Bitmap bitmap = BitmapPool.get(videoName);
                mVideoCover.setTag(R.id.video_cover_1, postContent);
                if (bitmap != null) {
                    //setThumbnail(bitmap);
                    //loadThumbnail(bitmap, postContent, mVideoCover);
                    loadThumbnail(bitmap, mVideoCover);
                } else {
                    //获取cache中的bitmap
                    // bitmap = ImageUtil.getCacheVideoThumbnail(videoName);
                    File file = ImageUtil.geCacheVideoThumbnailFile(videoName);
                    if (file.exists()) {
                        //loadThumbnail(file, postContent, mVideoCover);
                        loadThumbnail(file, mVideoCover);
                    } else {
                        //获取网络缩略图之前先显示默认图
                        loadThumbnail(null, mVideoCover);

                        //loadThumbnail(null, postContent, mVideoCover);
                        boolean isCreateThumbnailThreadRunning = BitmapPool.isCreateThumbnailThreadRunning(videoName);
                        if (!isCreateThumbnailThreadRunning) {//如果创建缩略图的线程没有正在运行，新建线程获取缩略图（避免开启多个线程）
                            BitmapPool.setIsCreateThumbnailThreadRunning(videoName, true);//1.标记线程正在运行
                            new LoadBitmapAsyncTask(mVideoCover, postContent).executeOnExecutor(AsyncTask.SERIAL_EXECUTOR);//AsyncTask.THREAD_POOL_EXECUTOR
                        }
                    }
                }

                videoContainer.setOnClickListener(new OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        //tbs内核加载成功
                        if (EnvironmentVariable.getProperty("tbsLoadResult", "false").equals("true")) {

                            //调用腾讯视频浏览服务
//                            if (TbsVideo.canUseTbsPlayer(getContext())) {
//                                TbsVideo.openVideo(getContext(), videoUrl);
//
//                            } else {
                            Intent intent = new Intent(getContext(), PlayerActivity.class);
                            intent.putExtra("videoPath", videoUrl);
                            intent.putExtra("videoName", videoName);
                            getContext().startActivity(intent);
                            //  }

                        } else {
                            Intent intent = new Intent(getContext(), PlayerActivity.class);
                            intent.putExtra("videoPath", videoUrl);
                            intent.putExtra("videoName", videoName);
                            getContext().startActivity(intent);
                        }

                    }
                });

            } else if (type == 4) {
                //网页
                mNinePhotoLayout.setVisibility(View.GONE);
                zoneNinePhotoLayout.setVisibility(View.GONE);
                videoContainer.setVisibility(GONE);
                mWebView.setVisibility(VISIBLE);

                //ViewGroup.LayoutParams layoutParams = mWebView.getLayoutParams();
                final JSONObject web = postContent.getJSONObject("web");
//                layoutParams.height = DensityUtil.dp2px(web.getInt("height"));
//                mWebView.setLayoutParams(layoutParams);
                mWebView.getWebClickView().setOnClickListener(new OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        Intent intent = new Intent(getContext(), ChatWebViewActivity.class);
                        try {
                            intent.putExtra("url", web.getString("url"));
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        getContext().startActivity(intent);
                    }
                });
//                mWebView.setWebViewClient(new WebViewClient() {
//                    @Override
//                    public boolean shouldOverrideUrlLoading(WebView view, String url) {
//                        Intent intent = new Intent(getContext(), ChatWebViewActivity.class);
//                        intent.putExtra("url", url);
//                        getContext().startActivity(intent);
//                        return true;//表示自己处理url跳转                    }
//                    }
//                });
                mWebView.loadUrl(web.getString("url"));
            } else {
                mNinePhotoLayout.setVisibility(View.GONE);
                zoneNinePhotoLayout.setVisibility(View.GONE);
                videoContainer.setVisibility(GONE);

            }

        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    /**
     * 说说样式
     *
     * @param userName
     * @param objType
     */

    public void ownStyle(String userName, int objType) {
        if (objType == 1) {
            mPhotoContainer.setVisibility(GONE);
        } else {
            mPhotoContainer.setVisibility(VISIBLE);
        }
        mPhotoContainer.setBackgroundColor(getResources().getColor(R.color.frame_white_background_color));
        mTransmitSourceUserName.setVisibility(GONE);
        mTransmitSourceUserName.setText(userName);
        tvTransmitContentDescirbe.setVisibility(GONE);
        tvTransmitContentDescirbe.setText("");
    }

    /**
     * 转发说说的样式
     *
     * @param transmitContent
     * @param text
     * @param userName
     */
    public void transmitStyle(Object transmitContent, String text, String userName) {
        mPhotoContainer.setBackgroundColor(getResources().getColor(R.color.frame_gray_background_color));
        mTransmitSourceUserName.setVisibility(VISIBLE);
        tvContentDescribe.setVisibility(VISIBLE);
        tvContentDescribe.setText(transmitContent.toString());
        mTransmitSourceUserName.setText(String.format("%1$s:", userName));
        mTransmitSourceUserName.setTextColor(getResources().getColor(R.color.mobile_zone_like_comment_people_textcolor));
        if (text == null || "".equals(text)) {
            tvTransmitContentDescirbe.setVisibility(GONE);
        } else {
            tvTransmitContentDescirbe.setVisibility(VISIBLE);
        }
        tvTransmitContentDescirbe.setText(text);
//        LinearLayout.LayoutParams layoutParams = (LinearLayout.LayoutParams) tvContentDescribe.getLayoutParams();
//        int margin = DensityUtil.dp2px(10);
//        layoutParams.setMargins(margin, margin, margin, 0);
//        tvContentDescribe.setLayoutParams(layoutParams);
//        LinearLayout.LayoutParams layoutParams1 = (LinearLayout.LayoutParams) mTransmitSourceUserName.getLayoutParams();
//        int margin1 = DensityUtil.dp2px(10);
//        layoutParams.setMargins(margin1, margin1, margin1, 0);
//        mTransmitSourceUserName.setLayoutParams(layoutParams1);
    }

    /**
     * 原说说被删除后的样式
     *
     * @param text
     */
    public void sourceContentDeleteStyle(String text) {
        mPhotoContainer.setBackgroundColor(getResources().getColor(R.color.frame_gray_background_color));
        mTransmitSourceUserName.setVisibility(VISIBLE);
        tvContentDescribe.setVisibility(VISIBLE);
        tvContentDescribe.setText(text);
        mTransmitSourceUserName.setText(R.string.zone_ss_is_delete);
        mTransmitSourceUserName.setTextColor(getResources().getColor(R.color.mobile_zone_like_comment_people_textcolor));
//        LinearLayout.LayoutParams layoutParams1 = (LinearLayout.LayoutParams) mPhotoContainer.getLayoutParams();
//        layoutParams1.setMargins(0, 0, 0, 0);
//        mPhotoContainer.setLayoutParams(layoutParams1);
//        LinearLayout.LayoutParams layoutParams = (LinearLayout.LayoutParams) mTransmitSourceUserName.getLayoutParams();
//        int margin = DensityUtil.dp2px(10);
//        layoutParams.setMargins(margin, margin, margin, margin);
//        mTransmitSourceUserName.setLayoutParams(layoutParams);

        tvTransmitContentDescirbe.setVisibility(GONE);
        mNinePhotoLayout.setVisibility(View.GONE);
        zoneNinePhotoLayout.setVisibility(View.GONE);
        videoContainer.setVisibility(GONE);
        mWebView.setVisibility(GONE);
    }

    /**
     * 设置所有内容的显示与隐藏
     *
     * @param isVisible
     */

    public void setAllViewVisibility(int isVisible) {
        tvContentDescribe.setVisibility(isVisible);
        mNinePhotoLayout.setVisibility(isVisible);
        zoneNinePhotoLayout.setVisibility(isVisible);
    }

    /**
     * 设置文字view的显示与隐藏
     *
     * @param isVisible
     */
    public void setTextContentVisibility(int isVisible) {
        tvContentDescribe.setVisibility(isVisible);
        zoneNinePhotoLayout.setVisibility(isVisible);
    }

    /**
     * 设置九宫格的显示与隐藏
     *
     * @param isVisible
     */
    public void setNinePhotoLayoutVisibility(int isVisible) {
        mNinePhotoLayout.setVisibility(isVisible);
        zoneNinePhotoLayout.setVisibility(isVisible);
    }

    public void setText(String text) {
        if (text != null) {
            tvContentDescribe.setText(text);
//            tvContentDescribe.setCloseText(text);
        } else {
            tvContentDescribe.setText("");
//            tvContentDescribe.setCloseText("");
        }
    }

    public void setDelegate(BGANinePhotoLayout.Delegate delegate) {
        mNinePhotoLayout.setDelegate(delegate);
    }

    /**
     * 设置缩略图
     *
     * @param
     */
//    private void setThumbnail(Bitmap bitmap) {
//        if (bitmap == null) {
//            mVideoCover.setImageDrawable(null);
//        } else {
//            BitmapDrawable drawable = new BitmapDrawable(bitmap);
//            drawable.setDither(true);
//            mVideoCover.setImageDrawable(drawable);
//        }
//    }


    private class LoadBitmapAsyncTask extends AsyncTask<String, Integer, Bitmap> {
        private JSONObject postContent;
        private String url;
        private ImageView iv;

        public LoadBitmapAsyncTask(ImageView iv, JSONObject postContent) {
            super();
            this.iv = iv;
            this.postContent = postContent;
        }

        @Override
        protected Bitmap doInBackground(String... params) {
            url = postContent.optString("video");
            Bitmap bitmap = null;

            //通过url截取文件名
            String videoName = PansoftCloudUtil.getPansoftCloudFileId(url);


            Bitmap cacheBitmap = BitmapPool.get(videoName);
            if (cacheBitmap != null) {
                return cacheBitmap;
            }
            bitmap = ImageUtil.getVideoThumbnail(url, 1200, 600);
            if (bitmap != null){
                ImageUtil.saveCacheVideoThumbnail(bitmap, videoName);
                BitmapPool.putBitmapInPool(videoName, bitmap);
            }
            return bitmap;
        }

        @Override
        protected void onPostExecute(Bitmap bitmap) {
            super.onPostExecute(bitmap);
            String videoName = PansoftCloudUtil.getPansoftCloudFileId(url);
            loadThumbnail(bitmap, postContent, iv);
            BitmapPool.setIsCreateThumbnailThreadRunning(videoName, false);//2.标记线程运行结束
            if (bitmap != null) {
                listener.finish();
            }

        }


    }

    /**
     * 加载缩略图
     *
     * @param imageObject
     * @param postContent
     * @param iv
     */
    private void loadThumbnail(Object imageObject, JSONObject postContent, ImageView iv) {
        if (mVideoCover.getTag(R.id.video_cover_1) == postContent ) {//如果View中数据数据还是原来的数据
            if (imageObject == null) {
                //imageObject = getResources().getDrawable(R.drawable.default_img);
                imageObject=postContent.optString("video");
            }
        Glide.with(getContext()).load(imageObject)
                .apply(new RequestOptions()
                        .diskCacheStrategy(DiskCacheStrategy.ALL))
                .into(iv);
        }
    }

    /**
     * 加载缩略图
     *
     * @param imageObject
     * @param iv
     */
    private void loadThumbnail(Object imageObject, ImageView iv) {
        if (imageObject == null) {
            imageObject = getResources().getDrawable(R.drawable.default_img);
        }
        Glide.with(getContext()).load(imageObject)
                .apply(new RequestOptions()
                        .diskCacheStrategy(DiskCacheStrategy.ALL))
                .into(iv);

    }


    public interface ThumbDisplayListener {
        void finish();
    }

    public void setOnLoadFinishLisner(ThumbDisplayListener listener) {
        this.listener = listener;
    }

    public static class BitmapPool {
        private static final int MAX_SIZE = 20;
        private static LinkedHashMap<String, Bitmap> bitmapPool = new LinkedHashMap<>(MAX_SIZE);
        //是否线程中正在生成缩略图，如果线程中正在生成缩略图，不再开启线程取bitmap
        private static Map<String, Boolean> isCreateThumbnailThreadRunningMap = new HashMap<>();

        private static synchronized void putBitmapInPool(String key, Bitmap bitmap) {
            if (bitmapPool.size() >= MAX_SIZE) {
                String firstKey = bitmapPool.keySet().iterator().next();
                bitmapPool.remove(firstKey);
            }
            bitmapPool.put(key, bitmap);
        }

        private static Bitmap get(String key) {
            return bitmapPool.get(key);
        }

        private static boolean isCreateThumbnailThreadRunning(String key) {
            Boolean bool = isCreateThumbnailThreadRunningMap.get(key);
            return bool == null ? false : bool;
        }

        private static void setIsCreateThumbnailThreadRunning(String key, boolean isCreateThumbnailThreadRunning) {
            isCreateThumbnailThreadRunningMap.put(key, isCreateThumbnailThreadRunning);
        }

        public static void release() {
            bitmapPool.clear();
            isCreateThumbnailThreadRunningMap.clear();
        }

    }

}
